﻿using Dm.Config;
using Furion;
using Furion.DataValidation;
using Furion.EventBus;
using GMS.NET.Const;
using GMS.NET.Core.ApiSafe;
using GMS.NET.Core.Tools;
using GMS.NET.Core.Users;
using Microsoft.AspNetCore.Mvc.Filters;

namespace GMS.NET.Web.Core.IFilters
{
    /// <summary>
    /// api操作拦截器
    /// </summary>
    public class ApiFilter : IAsyncActionFilter
    {
        private readonly IEventPublisher events = App.GetService<IEventPublisher>();

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 获取请求上下文
            var httpContext = context.HttpContext;
            var httpRequest = httpContext.Request;

            // 获取安全参数请求头
            var ApiTimestampHeader = httpRequest.Headers
                .TryGetValue(ApiHeaderConst.Timestamp, out var apiTimestampHeader)
                ? apiTimestampHeader.ToString()
                : null;
            var ApiSignatureHeader = httpRequest.Headers
                 .TryGetValue(ApiHeaderConst.Signature, out var apiSignatureHeader)
                 ? apiSignatureHeader.ToString()
                 : null;

            // 校验安全参数
            var apiSafeDto = new ApiSafeHeader() { Timestamp = ApiTimestampHeader, Signature = ApiSignatureHeader };
            var result = apiSafeDto.TryValidate();

            await events.PublishAsync(EventBusConst.LogsWriteApi,
                $"{UserInfo.UserId ?? ApiTool.GetIp()}{SplitCharConst.α}{httpRequest.Path}{SplitCharConst.α}{(result.IsValid ? "请求成功" : "非法签名,请求失败")}{SplitCharConst.α}{httpRequest.Scheme}{SplitCharConst.α}{httpRequest.Method}{SplitCharConst.α}{httpRequest.Protocol}{SplitCharConst.α}{httpRequest.ContentType}");

            if (result.IsValid) await next(); else result.ThrowValidateFailedModel();
        }
    }
}
